package io.github.enbool.controller;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.github.enbool.domain.User;
import io.github.enbool.service.DeviceService;
import io.github.enbool.service.UserService;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class AuthController {
	
	@Autowired
	private DeviceService deviceService;
	@Autowired
	private UserService userService;
	@Autowired
	private PasswordEncoder BCryptPasswordEncoder;

	@PostMapping("/mqtt/auth")
	public void auth(@RequestParam String clientid,	@RequestParam String username, @RequestParam String password,
			HttpServletResponse response) {
		log.info("auth");
		// 设备认证通过
		if(deviceService.auth(clientid, username, password)) {
			response.setStatus(HttpStatus.OK.value());
			return;
		}
		// 系统用户认证通过
		User user = (User) userService.loadUser(username);
		
		if(user != null) {			
			if(BCryptPasswordEncoder.matches(password, user.getPassword())) {
				response.setStatus(HttpStatus.OK.value());
				return;
			}				
		}	
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
	}
	
	@GetMapping("/mqtt/acl")
	public void acl(@RequestParam String access, @RequestParam String clientid, @RequestParam String username, @RequestParam String password,
			@RequestParam String ipaddr, @RequestParam String topic, HttpServletResponse response) {
		log.info("acl");
		response.setStatus(HttpStatus.OK.value());
	}
	
	@PostMapping("/mqtt/superuser")
	public void superuser(@RequestParam String clientid, @RequestParam String username,
			HttpServletResponse response) {
		log.info("superuser");
		response.setStatus(HttpStatus.OK.value());
	}
}
